﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    CANsetting = new CANParamSetting();
    canthread = new CANThread();
    protocolHand = new ProtocolThrend();

//    QThread thread;
//    protocolHand->moveToThread(&thread);
//    QObject::connect(canthread,&CANThread::getProtocolData,protocolHand,&ProtocolThrend::protocolHand);
//    thread.start();

    connect(canthread,&CANThread::getProtocolData,this,&MainWindow::displayText);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()//参数设置
{
    CANsetting->show();
}

void MainWindow::on_pushButton_2_clicked()//启动CAN
{
    if(ui->pushButton_2->text() == tr("CAN启动"))
    {
        ui->pushButton->setEnabled(false);
        ui->pushButton_2->setText(tr("CAN关闭"));
        canthread->deviceType = CANsetting->CANtype;
        canthread->debicIndex = CANsetting->index;
        canthread->baundRate = CANsetting->baundRate;
        canthread->debicCom = CANsetting->devicCOM;
        bool dev = canthread->openCAN();
        if(dev == true)
             canthread->start();
    }
    else if(ui->pushButton_2->text() == tr("CAN关闭"))
    {
        ui->pushButton->setEnabled(true);
        ui->pushButton_2->setText(tr("CAN启动"));
        canthread->stop();
        canthread->closeCAN();
    }
}

void MainWindow::on_pushButton_3_clicked()//发送
{
//    char ptr[] = "yaoyaoyao9527dalishenkejiyouxiangongsi";
    int ID = ui->lineEdit->text().toInt();
    QByteArray data;
    data.append(ui->textEdit->toPlainText().toHtmlEscaped());
    char* str = data.data();
    canthread->sendData(ID,(unsigned char*)str);
}

void MainWindow::displayText(VCI_CAN_OBJ *vci,DWORD dwRel)
{
//    qDebug()<<"from thread slot:";
    QByteArray data;
    for(int i = 0;i<dwRel;i++)
    {
        for(int j = 0;j<8;j++)
            data.append(vci[i].Data[j]);
    }
    QString str(data);
    ui->textEdit_2->setText(str);
}

